// index.js
// 获取应用实例
const app = getApp()

Component({
  data: {
    jokeList: [],
    picList: [
      {
        src: "/static/image/pic/baoyu.jpg"
      },
      {
        src: "/static/image/pic/dayu.jpg"
      },
      {
        src: "/static/image/pic/default.jpg"
      },
      {
        src: "/static/image/pic/duoyun.jpg"
      },
      {
        src: "/static/image/pic/baoyu.jpg"
      },
      {
        src: "/static/image/pic/leizhenyu.jpg"
      },
      {
        src: "/static/image/pic/qing.jpg"
      },
      {
        src: "/static/image/pic/wu.jpg"
      },
      {
        src: "/static/image/pic/xiaoxue.jpg"
      },
      {
        src: "/static/image/pic/xiaoyu.jpg"
      }
    ],
    page: 1,
    isMoveToUp: true,
  },
  methods: {
    onRefresh() {
      this.setData({                       //MoveToUp触发
        isMoveToUp: false
      })
      setTimeout(() => {
        // this.retrieve()
        console.log("我在刷新")
        wx.stopPullDownRefresh()
      }, 1000)
    },
    // 事件处理函数
    loadMore() {
      console.log("我在加载")
      ++this.data.page
      this.retrieve()
    },
    async retrieve() {
      wx.showLoading({
        title: '加载中',
      });
      
      let tempArr = []
      let url = `https://autumnfish.cn/api/joke`
      for(let i=0; i<10; i++) {
        let res = await new Promise(function(resolve, reject) {
          wx.request({
            url: url,
            success(res) {
              resolve(res)
            },
            fail(err) {
              reject(err)
            },
            complete() {
              wx.hideLoading()
            }
          })
        })
  
        tempArr.push({
          id: "text_" + i,
          title: res.data.substr(0, 4),
          content: res.data.replace(/<br\/>/g, '\n')
        })
      }
  
      let picTempArr = this.data.picList.map((item, index, arr) => {
        return {
          id: tempArr[index].id,
          title: tempArr[index].title,
          content: tempArr[index].content,
          src: item.src
        }
      })
  
      this.setData({
        jokeList: tempArr,
        picList: picTempArr
      })
    },
  },
  lifetimes: {
    attached: function() {
      // 在组件实例进入页面节点树时执行
      this.retrieve()
    },
    detached: function() {
      // 在组件实例被从页面节点树移除时执行
    },
  },
  pageLifetimes: {
    show() {
      // 页面被展示
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 0
        })
      }
    },
    hide: function() {
      // 页面被隐藏
    },
    resize: function(size) {
      // 页面尺寸变化
    }
  }
})
